//
//  STPhotoBrowserController.m
//  STTools
//
//  Created by stoneobs on 16/10/10.
//  Copyright © 2016年 stoneobs. All rights reserved.
//

#import "STBWBrowserViewController.h"

@interface STBWBrowserViewController ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
STBWBrowserCollectionViewCellDelegate>

@property(nonatomic,strong)NSMutableArray<STBWPhotoModel*>     *dataSouce;
@property(nonatomic,assign)NSInteger                            curentIndex;//传入进来的照片位置
@property(nonatomic,strong)NSIndexPath                          *curentIndexpath;//当前被浏览的照片位置

//top
@property(nonatomic,strong)UIView                               *topView;//顶部view
@property(nonatomic,strong)UIButton                             *titleButton;
@property(nonatomic,strong)UIButton                             *rightButton;
//底部
@property(nonatomic,strong)UIView                               *bootView;//顶部view
@property(nonatomic,strong)UIButton                             *originButton;//查看原图

//模态这个vc的控制器
@property(nonatomic,strong)UIView                               *currentView;//当前被放大的view（上一个控制器中的）
@property(nonatomic,strong)UIView                               *whiteView;//动画view,将当前图片变成白色区域
@property(nonatomic,assign)CGPoint                              startPoint;//上次移动的位置
@property(nonatomic,assign)CGFloat                              scale;//缩放比例
//展示开始动画的时候在collectionview上蒙上一层黑色的view，因为网络太快，或者原图存在的时候，那么在viewDidAppear中会先显示cell中的图片，在进行动画，造成一闪而过，体验不佳,所以添加这个view
@property(nonatomic,strong)UIView                               *beginView;

@property(nonatomic,assign)BOOL                                  didShowBeginAnimation;//是否展示过了入场动画，展示过就不展示了，当此vc不是最后一个时，应该不显示动画

@end

@implementation STBWBrowserViewController
- (instancetype)initWithArray:(NSArray<STBWPhotoModel *> *)dataSouce curentIndex:(NSInteger)curentIndex{
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
        if (dataSouce.count == 0) {
            NSAssert(NO, @"STPhotoBrowserController数组不能为空");
        }
        if (![dataSouce.firstObject isKindOfClass:[STBWPhotoModel class]]) {
            NSAssert(NO, @"dataSouce数组中的类型必须是STBWPhotoModel");
        }
        self.dataSouce = [NSMutableArray arrayWithArray:dataSouce];
        self.curentIndex = curentIndex;
        self.startPoint = UIApplication.sharedApplication.delegate.window.center;
        self.scale = 1;
        self.minZoomScale = 0.8;
    }
    return self;
}
//- (void)setShouldHideExcessiveAnimation:(BOOL)shouldHideExcessiveAnimation{
//    _shouldHideExcessiveAnimation = shouldHideExcessiveAnimation;
//    if (shouldHideExcessiveAnimation) {
//        if (@available(iOS 13.0, *)) {
//            self.modalPresentationStyle = UIModalPresentationAutomatic;
//        } else {
//            // Fallback on earlier versions
//        }
//    }else{
//        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
//    }
//}
- (void)setShouldHideVisualEffectView:(BOOL)shouldHideVisualEffectView{
    _shouldHideVisualEffectView = shouldHideVisualEffectView;
    for (STBWPhotoModel* model in self.dataSouce) {
        model.shouldHideVisualEffectView = shouldHideVisualEffectView;
    }
    [self.collectionView reloadData];
    
}
#pragma mark --SubView
- (void)initSubviews{
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, STBW_SCREEN_WIDTH, [self navgationBarBootom])];
    self.topView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    self.topView.layer.shadowOffset = CGSizeMake(0, 0.8);
    self.topView.layer.shadowColor = [UIColor grayColor].CGColor;
    self.topView.layer.shadowRadius = 1;
    self.topView.layer.shadowOpacity = .5f;
    CGRect shadowFrame = self.topView.layer.bounds;
    CGPathRef shadowPath = [UIBezierPath
                            bezierPathWithRect:shadowFrame].CGPath;
    self.topView.layer.shadowPath = shadowPath;
     UIImage * image = [self getImageWithBoudleName:@"stoneobs_browser" imgName:@"stbw_img_back"];
    //返回按钮 -之后点击哪个view就返回到哪个view
    UIButton * cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 44, 44)];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
    cancelButton.backgroundColor = [UIColor clearColor];
    cancelButton.stbw_bottom = self.topView.stbw_height;
    [cancelButton setImage:image forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(didClicReturnBack) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:cancelButton];
    
    //title
    self.titleButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 0, 100, 44)];
    [self.titleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.titleButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.titleButton setTitle:@"" forState:UIControlStateNormal];
    self.titleButton.stbw_bottom = self.topView.stbw_height;
    self.titleButton.stbw_centerX = STBW_SCREEN_WIDTH/2;
    self.titleButton.backgroundColor = [UIColor clearColor];
    self.titleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.topView addSubview:self.titleButton];
    
   
    
    //更多按钮
    self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(STBW_SCREEN_WIDTH-44-10, 0, 44, 44)];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.rightButton setTitle:@"" forState:UIControlStateNormal];
    self.rightButton.stbw_bottom = self.topView.stbw_height;
    self.rightButton.backgroundColor = [UIColor clearColor];
    self.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    UIImage * normalImage =  [self getImageWithBoudleName:@"stoneobs_browser" imgName:@"stbw_img_white_more"];
    [self.rightButton setImage:normalImage forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(rightBarAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.rightButton];
    [self.view addSubview:self.topView];
    
    
}

- (void)initBottomView
{
    
    self.bootView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, STBW_SCREEN_WIDTH, [self tabBarTop] + 49)];
    self.bootView.layer.shadowOffset = CGSizeMake(0, -0.8);
    self.bootView.layer.shadowColor = [UIColor grayColor].CGColor;
    self.bootView.layer.shadowRadius = 1;
    self.bootView.layer.shadowOpacity = .5f;
    CGRect shadowFrame = self.bootView.layer.bounds;
    CGPathRef shadowPath = [UIBezierPath
                            bezierPathWithRect:shadowFrame].CGPath;
    self.bootView.layer.shadowPath = shadowPath;
    
    [self.bootView setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.5]];
    
    
    //原图按钮
    self.originButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 0, 200, 20)];
    self.originButton.stbw_centerY = 25;
    self.originButton.stbw_centerX = self.bootView.stbw_width/2;
    [self.originButton setTitleColor:self.themeColor forState:UIControlStateNormal];
    [self.originButton setTitle:@"原图" forState:UIControlStateNormal];
    [self.originButton addTarget:self action:@selector(didClicTheOriginButton) forControlEvents:UIControlEventTouchUpInside];
    self.originButton.titleLabel.font = [UIFont systemFontOfSize:13];
    self.originButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.bootView addSubview:self.originButton];
    
    [self.view addSubview:self.bootView];
    
    self.topView.stbw_bottom = 0;
    self.bootView.stbw_top = STBW_SCREEN_HEIGHT;
    
    
}
#pragma mark --vc生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor clearColor];
    
    UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    [flow setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, STBW_SCREEN_WIDTH, STBW_SCREEN_HEIGHT) collectionViewLayout:flow];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.alwaysBounceVertical = NO;
    self.collectionView.alwaysBounceHorizontal = YES;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor= [UIColor blackColor];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[STBWCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [self.view addSubview:self.collectionView];
    //改在collectionview上面
    [self initSubviews];
    [self initBottomView];
    
    if (self.curentIndex > 0) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.curentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    
    if (!self.shouldHideExcessiveAnimation) {
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pangesHandle:)];
        [self.view addGestureRecognizer:pan];
    }
    if (self.shouldHideTopView) {
        self.topView.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.didShowBeginAnimation) {
        return ;
    }
    //原图
    if (self.themeColor) {
        [self.originButton setTitleColor:self.themeColor forState:UIControlStateNormal];
        [self.originButton setTitle:@"原图" forState:UIControlStateNormal];
    }
    
    
    
    self.beginView = [[UIView alloc] initWithFrame:STBW_SCREEN_FRAME];
    self.beginView.backgroundColor = [UIColor blackColor];
    if (!self.shouldHideExcessiveAnimation) {
       [self.view addSubview:self.beginView];
    }
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.shouldHideExcessiveAnimation) {
        [self.collectionView reloadData];
    }else{
        [self scrollViewDidScroll:self.collectionView];
        [self scrollViewDidEndDecelerating:self.collectionView];
        [self showBeginAnimation];
    }

    
}

#pragma --mark UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(STBW_SCREEN_WIDTH, STBW_SCREEN_HEIGHT);
}
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    STBWCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    for (UIGestureRecognizer * ges in item.imageView.gestureRecognizers) {
        [item.imageView removeGestureRecognizer:ges];
    }
    item.model = self.dataSouce[indexPath.item];
    item.delegate = self;
    return item;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    STBWCollectionViewCell * mycell = (STBWCollectionViewCell*)cell;
    //回到初始状态
    [mycell backToOrigin];
}
#pragma --mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
#pragma mark --STCollectionViewCellDelegate
//点击事件
- (void)didClicTheImageView:(UIImageView *)imageView cell:(STBWCollectionViewCell *)cell{
    //增加适中的震感反馈
    if (cell.scrollView.zoomScale > 1) {
        [cell.scrollView setZoomScale:1 animated:YES];
    }
    if (@available(iOS 10.0, *)) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
            [generator prepare];
            [generator impactOccurred];
        });
        
    } else {
        // Fallback on earlier versions
    }
    self.scale = 1;
    [self showDismisAnimation];
}
- (void)didZoomScale:(CGFloat)scale cell:(STBWCollectionViewCell *)cell imageView:(UIImageView *)imageView{
    CGFloat minscale = self.minZoomScale;
    if (scale > 1) {
        self.collectionView.backgroundColor = UIColor.blackColor;
    }else if (scale<= minscale){
        
        self.collectionView.backgroundColor = UIColor.clearColor;
        self.scale = minscale;
        [self backToLastVC];
    }else{
        CGFloat chazhi = scale - minscale;
        CGFloat current = 1 - scale;
        self.collectionView.backgroundColor =  [UIColor.blackColor colorWithAlphaComponent:1 - current / chazhi];
    }
}
#pragma mark --UIScrollViewDeleagte
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.collectionView) {
        CGFloat width = scrollView.contentOffset.x;
        NSInteger num = (width + 2) /STBW_SCREEN_WIDTH;//+2是为了获取争取的num
        self.curentIndexpath = [NSIndexPath indexPathForRow:num inSection:0];
        if (self.delegate && [self.delegate respondsToSelector:@selector(browserControllerDidScrollToIndexpath:model:controller:)]) {
            self.currentView =  [self.delegate browserControllerDidScrollToIndexpath:self.curentIndexpath
                                                                               model:self.dataSouce[_curentIndexpath.item]
                                                                          controller: self];
            
            //添加whiteView
            [self.whiteView removeFromSuperview];
            self.whiteView = [[UIView alloc] initWithFrame:self.currentView.bounds];
            self.whiteView.backgroundColor = [UIColor whiteColor];
            self.whiteView.hidden = NO;
            [self.currentView addSubview:self.whiteView];
        }
        
        [self.titleButton setTitle:[NSString stringWithFormat:@"%ld/%ld",num+1,self.dataSouce.count] forState:UIControlStateNormal];
        STBWPhotoModel * model = self.dataSouce[_curentIndexpath.item];
        if (model.originImage.size.width > 10) {
            self.originButton.selected = YES;
            [self.originButton setTitle:[NSString stringWithFormat:@"原图(%@)",[self sizeFromImage:model.originImage]] forState:UIControlStateNormal];
        }else{
            [self.originButton setTitle:@"原图" forState:UIControlStateNormal];
        }
        if (num == self.curentIndexpath.row) {
            //如果在当前cell的scrollview滑动中触发了 collectionView 的这个方法，则不用回到初始状态
            return;
        }
        for (STBWCollectionViewCell * cell in self.collectionView.visibleCells) {
            [cell backToOrigin];
        }
    }
}

#pragma mark --Action Method
- (void)pangesHandle:(UIPanGestureRecognizer*)pan{
    CGPoint location = [pan locationInView:self.view];
    CGPoint point = [pan translationInView:self.view];
    STBWCollectionViewCell *cell = (STBWCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:self.curentIndexpath];
    if (pan.state == UIGestureRecognizerStateBegan) {
        _startPoint  = point;
    }else{
        //向上移动不处理
        if (location.y - _startPoint.y < 0 ) {
            return;
        }
        UIImageView * imageView = cell.imageView;
        if (!imageView.image) {
            return;
        }
        CGPoint translation = [pan translationInView:self.view];
        imageView.center = CGPointMake(imageView.center.x + translation.x,
                                       imageView.center.y + translation.y);
        [pan setTranslation:CGPointZero inView:self.view];
        
        
        
        //记录原始frame
        UIImageView * tempImageView = UIImageView.new;
        UIImage * image = imageView.image;
        CGFloat imagebilie = image.size.height / image.size.width;
        CGSize dealSize = CGSizeMake(STBW_SCREEN_WIDTH, STBW_SCREEN_WIDTH * imagebilie);
        tempImageView.stbw_size = dealSize;
        tempImageView.center = UIApplication.sharedApplication.delegate.window.center;
        
        
        CGFloat centery = STBW_SCREEN_HEIGHT / 2;
        CGFloat y = imageView.stbw_centerY;
        CGFloat moveDistence = ABS(centery - y);
        
        CGFloat minscale = 0.7;//最小缩放比列
        CGFloat bilie = moveDistence / (STBW_SCREEN_WIDTH / 2);
        CGFloat toscale =  1 - (1-minscale)*bilie;
        
        self.collectionView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:toscale];
        //计算frame；
        CGPoint center = imageView.center;
        
        imageView.stbw_size = CGSizeMake(tempImageView.stbw_width * toscale, tempImageView.stbw_height * toscale);
        imageView.center = center;
        
        if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
            _startPoint = UIApplication.sharedApplication.delegate.window.center;
            if (toscale > minscale) {
                //回到初始位置
                [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0.7 options:UIViewAnimationOptionLayoutSubviews animations:^{
                    [cell backToOrigin];
                    self.collectionView.backgroundColor = UIColor.blackColor;
                } completion:^(BOOL finished) {
                    
                }];
                
            }else{
                [self showDismisAnimation];
            }
        }
    }
    
}

//点击右上角
- (void)rightBarAction{
    if (self.delegate && [self.delegate respondsToSelector:@selector(rightBarActionFromController:currentIndexPath:)]) {
        [self.delegate rightBarActionFromController:self currentIndexPath:self.curentIndexpath];
    }
}
//点击导航返回键
- (void)didClicReturnBack{
    [self backToLastVC];
}

//点击原图按钮
- (void)didClicTheOriginButton{
    
    self.originButton.selected = !self.originButton.selected;
    if (self.originButton.selected) {
        //请求大图
        STBWPhotoModel * model = self.dataSouce[_curentIndexpath.item];
        if (model.originImage.size.width > 10) {
            return;
        }else{
            [SDWebImageManager.sharedManager loadImageWithURL:[NSURL URLWithString:model.originImageUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                model.originImage = image;
                [self.originButton setTitle:[NSString stringWithFormat:@"原图(%@)",[self sizeFromImage:model.originImage]] forState:UIControlStateNormal];
                [self.collectionView reloadItemsAtIndexPaths:@[self.curentIndexpath]];
            }];
        }
    }
    
    
    
}

#pragma mark --Public Method
- (void)reloadData{
    [self.collectionView reloadData];
}
#pragma mark --Private Method
//退出控制器，之后添加动画
-(void)backToLastVC
{
    if (self.shouldHideExcessiveAnimation) {
        [self.whiteView removeFromSuperview];
        [self dismissViewControllerAnimated:1 completion:^{

        }];
    }else{
        [self dismissViewControllerAnimated:NO completion:^{
            if (self.shouldHideExcessiveAnimation) {
                
            }
            
            [self showDismisAnimation];
        }];
    }

    
}
//电池
-(BOOL)prefersStatusBarHidden
{
    return NO;
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
    
}
- (void)bottomAndTopViewAnimation{
    
    [UIView animateWithDuration:0.4 animations:^{
        if (!self.shouldHideTopView) {
            self.topView.stbw_top = 0;
        }
        if (!self.shouldHideBottomView) {
            self.bootView.stbw_top = [self tabBarTop];
        }
        
        
    }];
    
}
//开始动画
- (void)showBeginAnimation{
    
    if (self.didShowBeginAnimation) {
        return;
    }
    if (!self.shouldHideExcessiveAnimation) {
        self.collectionView.backgroundColor = [UIColor blackColor];
           UIImage    * nowImage;
           if ([self.currentView isKindOfClass:[UIImageView class]]) {
               UIImageView * imageView = (UIImageView*)self.currentView;
               nowImage = imageView.image;
               
           }
           if ([self.currentView isKindOfClass:[UIButton class]]) {
               UIButton * button = (UIButton*)self.currentView;
               nowImage = button.currentBackgroundImage;
               if (!nowImage) {
                   nowImage = button.currentImage;
               }
           }
           
           
           CGRect originframe = [self.currentView convertRect:_currentView.bounds toView:self.view.window];
           
           UIImageView *  visiouImageView = [[UIImageView alloc] initWithFrame:UIScreen.mainScreen.bounds];
           visiouImageView.image = nowImage;
            visiouImageView.contentMode = UIViewContentModeScaleAspectFill;
           [[UIApplication sharedApplication].keyWindow addSubview:visiouImageView];

           UIVisualEffectView * visualView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
           [visiouImageView addSubview:visualView];
           visualView.frame = visiouImageView.bounds;
           visiouImageView.alpha = 0;
           if (self.shouldHideVisualEffectView) {
               visiouImageView.hidden = YES;
           }
          
           [[UIApplication sharedApplication].keyWindow addSubview:visiouImageView];
           
           UIImageView *  animationImageView = [[UIImageView alloc] initWithFrame:originframe];
           animationImageView.image = nowImage;
           animationImageView.clipsToBounds = YES;
           animationImageView.contentMode = UIViewContentModeScaleAspectFit;
           [[UIApplication sharedApplication].keyWindow addSubview:animationImageView];
           
           //动画展示0.4
           CGFloat duration = 0.4;
           //use spring
           [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.9 options:UIViewAnimationOptionTransitionNone animations:^{
               animationImageView.frame = STBW_SCREEN_FRAME;
               animationImageView.center = self.view.center;
               visiouImageView.alpha = 1;
           } completion:^(BOOL finished) {
               [animationImageView removeFromSuperview];
               [visiouImageView removeFromSuperview];
               self.didShowBeginAnimation = YES;
               [self.beginView removeFromSuperview];
               [self bottomAndTopViewAnimation];
               
           }];
    }else{
        self.didShowBeginAnimation = YES;
        [self.beginView removeFromSuperview];
        [self bottomAndTopViewAnimation];
    }
   
    
    
    
    
    
}
//退出动画
-(void)showDismisAnimation{
    if (self.shouldHideExcessiveAnimation) {
        [self.whiteView removeFromSuperview];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(willDismissFromSTPhotoSystemBrowserControllerCurrentIndexPath:currentModel:controller:)]) {
        [self.delegate willDismissFromSTPhotoSystemBrowserControllerCurrentIndexPath:self.curentIndexpath
                                                                        currentModel:self.dataSouce[_curentIndexpath.item]
                                                                          controller:self];
    }
    self.topView.hidden = YES;
    self.bootView.hidden = YES;
    self.collectionView.scrollEnabled = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    STBWCollectionViewCell * mycell = (STBWCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:_curentIndexpath];
    mycell.imageView.hidden = YES;
    mycell.backgroundImageView.hidden = YES;
    CGRect frame ;
    frame = mycell.imageView.frame;
    
    UIImageView *  animationImageView = [[UIImageView alloc] initWithFrame:frame];
    if (self.scale != 1) {
        CGPoint center = animationImageView.center;
        animationImageView.stbw_size = CGSizeMake(animationImageView.stbw_width * self.scale,
                                                  animationImageView.stbw_height * self.scale);
        animationImageView.center = center;
    }
    
    animationImageView.image = mycell.imageView.image;
    animationImageView.clipsToBounds = YES;
    //animationImageView.backgroundColor = [UIColor redColor];
    animationImageView.contentMode = UIViewContentModeScaleAspectFill;
    [[UIApplication sharedApplication].keyWindow addSubview:animationImageView];
    
    //动画展示
    CGFloat duration = 0.4   ;
    if (self.delegate && [self.delegate respondsToSelector:@selector(browserControllerDidScrollToIndexpath:model:controller:)]) {
        self.currentView =  [self.delegate browserControllerDidScrollToIndexpath:self.curentIndexpath
                                                                           model:self.dataSouce[_curentIndexpath.item]
                                                                      controller: self];
        
    }
    UIView * nowView = self.currentView;
    [UIView animateWithDuration:duration animations:^{
        if (nowView) {
            
            CGRect frame = [nowView convertRect:nowView.bounds toView:self.view.window];
            animationImageView.frame = frame;
            
        }else
        {
            animationImageView.transform = CGAffineTransformMakeScale(1.4, 1.4);
            animationImageView.alpha = 0.1;
            animationImageView.center = self.view.center;
            
            
        }
        
    } completion:^(BOOL finished) {
        [animationImageView removeFromSuperview];
        [self.whiteView removeFromSuperview];
        [self dismissViewControllerAnimated:NO completion:^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(didDismissFromSTPhotoSystemBrowserControllerCurrentIndexPath:currentModel:controller:)]) {
                [self.delegate didDismissFromSTPhotoSystemBrowserControllerCurrentIndexPath:self.curentIndexpath
                                                                               currentModel:self.dataSouce[self.curentIndexpath.item]
                                                                                 controller:self];
            }
        }];
    }];
    
    
}

//获取图片大小
- (NSString *)sizeFromImage:(UIImage*)image{
    NSData * data = UIImageJPEGRepresentation(image,1);
    CGFloat  lengthKB = [data length]/1000;//1000最接近
    
    if (lengthKB < 1024) {
        return [NSString stringWithFormat:@"%0.02fk",lengthKB];
    }else{
        CGFloat lengthMb = lengthKB/1000;
        return [NSString stringWithFormat:@"%0.02fM",lengthMb];
    }
}
- (CGFloat)navgationBarBootom{
    
    UIWindow * window = UIApplication.sharedApplication.delegate.window;
    if (@available(iOS 11.0, *)) {
        if (window.safeAreaInsets.bottom) {
            return 88;
        }
    } else {
        // Fallback on earlier versions
    }
    
    return 64;
}
- (CGFloat)tabBarTop{
    
    UIWindow * window = UIApplication.sharedApplication.delegate.window;
    if (@available(iOS 11.0, *)) {
        if (window.safeAreaInsets.bottom) {
            return (STBW_SCREEN_HEIGHT - 83);
        }
    } else {
        // Fallback on earlier versions
    }
    
    return (STBW_SCREEN_HEIGHT - 49);
}
- (UIImage *)getImageWithBoudleName:(NSString *)boudleName imgName:(NSString *)imgName {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSURL *url = [bundle URLForResource:boudleName withExtension:@"bundle"];
    NSBundle *targetBundle = [NSBundle bundleWithURL:url];
    UIImage *image = [UIImage imageNamed:imgName
                                inBundle:targetBundle
           compatibleWithTraitCollection:nil];
    return image;
}
@end
